package com.colorlight.cloud.xm.entity.instructions;

import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.common.model.ExceptionEnum;
import com.colorlight.cloud.xm.api.XmEntityScheduleActions;
import com.colorlight.cloud.xm.entity.po.TimeData;
import com.colorlight.iot.proto.xm.instruction.XmInstruction;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.*;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Objects;

/**
 * 设置时间时区，支持网络同步
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class SetTimeZone implements XmEntityScheduleActions {

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputMsg implements Serializable {
        /**
         * 设置的时间时区
         */
        private TimeData time;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class OutputMsg implements Serializable {
        /**
         * 返回设置的时间时区
         */
        private TimeData time;
    }

    private InputMsg input;
    private OutputMsg output;

    @Override
    public ByteString objectConvertBytes() {
        final XmInstruction.SetTimeZone.InputMsg.Builder inputMsg =
                XmInstruction.SetTimeZone.InputMsg.newBuilder();
        InputMsg thisInput = this.getInput();
        inputMsg.setTime(thisInput.getTime().toProto());
        final XmInstruction.SetTimeZone.Builder builder =
                XmInstruction.SetTimeZone.newBuilder();
        builder.setInput(inputMsg);
        return builder.build().toByteString();
    }

    @Override
    public SetTimeZone byteConvertObject(ByteString bytes) {
        XmInstruction.SetTimeZone setTimeZone = null;
        try {
            setTimeZone = XmInstruction.SetTimeZone.parseFrom(bytes);
        } catch (InvalidProtocolBufferException e) {
            log.error("", e);
        }
        if (Objects.isNull(setTimeZone)) {
            throw new ParameterException(ExceptionEnum.MSG_PARAMETER_EXCEPTION);
        }
        OutputMsg outputMsg = new OutputMsg();
        XmInstruction.SetTimeZone.OutputMsg output = setTimeZone.getOutput();
        outputMsg.setTime(new TimeData().formProto(output.getTime()));
        this.setOutput(outputMsg);
        return this;
    }
}

